
let wxCharts = require('../../utils/wxcharts.js');
let lineChart = null;

function inArray(arr, key, val) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i][key] === val) {
            return i;
        }
    }
    return -1;
}

//字符串转buffer 十六进制
function stringToHexBuffer(data) {
    var typedArray = new Uint8Array(data.match(/[\da-f]{2}/gi).map(function (h) {
        return parseInt(h, 16)
    }))

    return typedArray.buffer
}

// 字符串转byte
function stringToBytes(str) {
    var array = new Uint8Array(str.length);
    for (var i = 0, l = str.length; i < l; i++) {
        array[i] = str.charCodeAt(i);
    }
    console.log(array);
    return array.buffer;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
    var hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
            return ('00' + bit.toString(16)).slice(-2)
        }
    )
    return hexArr.join('');
}

Page({
    data: {
        devices: [],
        connected: true,
        chs: [],
        datas: [],// 一个图表能容纳的数据数组
        secondDatas: [],// 刷新一次图表所能容纳数据的数组
        allDatas: [],// 发送后台数据容纳的数组
        // 三个轴的数据数组，如果是空数组，图表控件是不能绘制完成的，所以这里起始值不能给空数组
        xData: [0],
        yData: [0],
        zData: [0]
    },

    /////////////////////////  图表相关 /////////////////////////////

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function () {
        let that = this;
        let deviceId = wx.getStorageSync('DeviceId');
      
            //是否有已连接设备
    wx.getConnectedBluetoothDevices({
        success: function (res) {
            that.writeBLECharacteristicValue();
        },
        fail:function (res) {
            wx.showModal({
                title: '提示',
                content: '设备未连接，请连接设备',
                confirmText: "是",
                cancelText: "否",
                success: function (res) {
                    wx.navigateTo({
                        url: '../connectingBluetooth/connectingBluetooth'
                    })
                }
            });
        },
    })

        // 注：画布的高度在app.wxss中设置 这里设置画布的宽为屏幕的宽
        var windowWidth = 320;
        try {
            var res = wx.getSystemInfoSync();
            windowWidth = res.windowWidth;
        } catch (e) {
            console.error('getSystemInfoSync failed!');
        }

        var simulationData = this.createSimulationData();
        lineChart = new wxCharts({
            canvasId: 'lineCanvas',
            type: 'line',                          // 图表类型
            categories: simulationData.categories, // x轴坐标点
            // background: '#f5f5f5',
            series: [{
                name: 'X轴加速度',
                data: that.data.xData,
                format: function (val, name) {
                    return val.toFixed(2);
                }
            }, {
                name: 'Y轴加速度',
                data: that.data.yData,
                format: function (val, name) {
                    return val.toFixed(2);
                }
            }, {
                name: 'Z轴加速度',
                data: that.data.zData,
                format: function (val, name) {
                    return val.toFixed(2);
                }
            }],
            xAxis: {
                disableGrid: true
            },
            yAxis: {
                title: '',
                format: function (val) {
                    return val.toFixed(0);
                },
                min: -30,   // 固定最小值
                max: 30     // 固定最大值
            },
            width: windowWidth,               // 图表宽度
            height: 400,                      // 图表高度 注：需要和app.wxss中canvas设置保持一致
            dataLabel: false,                 // 是否显示每个点的数据
            dataPointShape: false,            // 每个点是否画点出来
            animation: false,                 // 是否需要动画展示 数据加载
            subtitle: '空间加速度X、Y、Z',      // 图表标题
            extra: {
                lineStyle: 'curve'
            }
        });
    },

    // 创建图表数据 x轴的坐标
    createSimulationData: function () {
        var categories = [];
        var data = [];
        for (var i = 0; i < 100; i++) {
            categories.push(i);
        }
        return {
            categories: categories
        }
    },

    // 刷新图表数据
    updateData: function () {
        var that = this;
        var simulationData = this.createSimulationData();
        var series = [{
            name: 'X轴加速度',
            data: that.data.xData,
            format: function (val, name) {
                return val.toFixed(2);
            }
        }, {
            name: 'Y轴加速度',
            data: that.data.yData,
            format: function (val, name) {
                return val.toFixed(2);
            }
        }, {
            name: 'Z轴加速度',
            data: that.data.zData,
            format: function (val, name) {
                return val.toFixed(2);
            }
        }];
        lineChart.updateData({
            categories: simulationData.categories,
            series: series
        });
    },
    /////////////////////////  蓝牙相关 /////////////////////////////
    //发送：同步指令
    writeBLECharacteristicValue() {
        let _this = this;
        let order = "AUTO_ACC";
        let buffer = stringToBytes(order);
        let deviceId = wx.getStorageSync('DeviceId');
        let serviceId = wx.getStorageSync('ServiceId');
        let characteristicId = wx.getStorageSync('CharacteristicId');
        wx.writeBLECharacteristicValue({
            deviceId: deviceId,
            serviceId: serviceId,
            characteristicId: characteristicId,
            value: buffer,
            success: function (res) {
                console.log("发送成功AUTO_ACC", res)
                _this.notifyBLECharacteristicValueChange()//接收消息
            },
            fail(res) {
                console.log("发送失败", res)
            }
        })
    },
    //方法
    notifyBLECharacteristicValueChange() {
        
        let _this = this;
        let deviceId = wx.getStorageSync('DeviceId');
        let serviceId = wx.getStorageSync('ServiceId');
        let characteristicId = wx.getStorageSync('CharacteristicId');
        wx.notifyBLECharacteristicValueChange({
            deviceId: deviceId,
            serviceId: serviceId,
            characteristicId: characteristicId,
            state: true,
            complete(res) {
                _this.onBLECharacteristicValueChange();//接受消息
            }
        });
    },
    //方法:接受消息
    onBLECharacteristicValueChange() {
        let that = this;
        wx.onBLECharacteristicValueChange((characteristic) => {
            const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
            console.log('监听同步返回数据2222', characteristic);
            // 一条数据 添加到这一秒数组中
            var xAF = new Float32Array(characteristic.value.slice(0, 4));
            var yAF = new Float32Array(characteristic.value.slice(4, 8));
            var zAF = new Float32Array(characteristic.value.slice(8, 12));
            var time = new Int32Array(characteristic.value.slice(12, 16));
            var itemData = {
                accelerationX: xAF[0],
                accelerationY: yAF[0],
                accelerationZ: zAF[0],
                time: time[0]
            };
            // 数据量超过300条 清空
            if (null != that.data.datas && that.data.datas.length > 100) {
                that.data.xData = [0];
                that.data.yData = [0];
                that.data.zData = [0];
                that.data.datas = [];
                that.data.secondDatas = [];
            }
            that.data.datas.push(itemData);
            that.data.allDatas.push(itemData);

            // 数据满5条刷新图表 即5*100ms刷新一次
            if (that.data.secondDatas.length > 5) {
                for (var i = 0; i < that.data.secondDatas.length; i++) {
                    that.data.xData.push(that.data.secondDatas[i].accelerationX == null ? 0 : that.data.secondDatas[i].accelerationX);
                    that.data.yData.push(that.data.secondDatas[i].accelerationY == null ? 0 : that.data.secondDatas[i].accelerationY);
                    that.data.zData.push(that.data.secondDatas[i].accelerationZ == null ? 0 : that.data.secondDatas[i].accelerationZ);
                };
                that.data.secondDatas = [];
                that.updateData();
            };
            that.data.secondDatas.push(itemData);
        });
    },
   
})
